<template>
  <div>
    <h1>个人资料</h1>
    <el-form class="stuDetail" label-width="auto" ref="form" :model="form">
      <el-form-item label="头像">
        <img :src="form.avatar" alt="">
        <span class="edit_touxiang" @click="showEditTouxiang"> <i class="iconfont icon-xiugaitouxiang" /> 修改头像</span>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="form.sex">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出生日期">
        <el-date-picker prefix-icon="el-icon-arrow-down" :clearable=false v-model="form.birthday" type="date" placeholder="选择日期"  style="width: 100%;"></el-date-picker>
      </el-form-item>
      <el-form-item label="账号">
        <el-input disabled v-model="form.usercode"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input class="password" disabled v-model="password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="学校">
        <el-input disabled v-model="form.schooleName"></el-input>
      </el-form-item>
      <el-form-item class="button">
        <el-button type="danger" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
    <!-- 修改头像对话框 -->
    <el-dialog 
      width="718px"
      title="修改头像"
      :visible.sync="touxiangDialog">
     <div class="touxiangDialog">
        <span class="txt">图片上传</span>
        <!-- 图片裁剪 -->
      <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :canMoveBox="options.canMoveBox"
            :canMove="options.canMove"
          >
      </vue-cropper>
      <el-upload
       ref="upload"
        name='file'
        action="action"
        :show-file-list="false"
        :on-change="change"
        :auto-upload="false"
        :http-request="uploadImg"
        :file-list="fileList"
      >
       <el-button type="danger" plain>点击上传</el-button>
       <div slot="tip" class="el-upload__tip">注：仅支持JPG、PNG格式，文件小于1M</div>
       <!-- <img :src="form.avatar" alt=""> -->
      </el-upload>
         <el-button class="save" type="danger" @click="uploadImg">保存</el-button>
     </div>
    </el-dialog>
  </div>
</template>

<script>
// import { VueCropper }  from 'vue-cropper' 
export default {
  name: "mine",
  components: {
    // VueCropper,
  },
  data(){
    return{
      touxiangDialog: false,
      password:'666666',
      form:{
        avatar:'',
        birthday:'',
        username:'',
        schooleName:'',
        usercode:'',
        sex:'',
        userid:''
      },
      //图片裁剪配置
      options: {
          img: '', //裁剪图片的地址
          info: true, //裁剪框的大小信息
          outputSize: 1, // 裁剪生成图片的质量
          outputType: '', // 裁剪生成图片的格式
          canScale: false, // 图片是否允许滚轮缩放
          canMove: true, //能否拖动图片
          canMoveBox: false, //能否拖动截图框
          autoCrop: true, //是否默认生成截图框
          autoCropWidth: 254, //默认生成截图框宽度
          autoCropHeight: 254,
          fixedBox: true, // 固定截图框大小 是否允许改变
          fixed: true, //是否开启截图框宽高固定比例
          fixedNumber: [1, 1], //截图框的宽高比例
          original: false, // 上传图片按照原始比例渲染
          centerBox: false, // 截图框是否被限制在图片里面
          infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
        },
        previews: {},
        loading: false,
        fileList: [],
        uploadAccept: ['jpeg', 'jpg', 'png']

    }
  },
  created(){
    this.getAppStuDetail()
  },
  methods:{
    //选择文件时的钩子
    change(file){
       let type = file.raw.type.split('/')[1];
        if (this.uploadAccept.indexOf(type) > -1) {
          // 上传允许的类型之内
          const reader = new FileReader()
          // 把Array Buffer转化为blob 如果是base64不需要
          // 转化为base64
          reader.readAsDataURL(file.raw)
          reader.onload = () => {
            this.options.img = reader.result
          }
        } else {
          this.$message.warning("您上传的图片格式不符，请重新上传")
        }
    },
    //自定义上传头像
    uploadImg(){  
        var filelist = new FormData(); 
        //获取裁剪后的图片（格式为base64）       
        this.$refs.cropper.getCropData((data) => {
          // 将base64 的图片转换成file对象上传 atob将ascii码解析成binary数据
          let binary = atob(data.split(',')[1]);
          let mime = data.split(',')[0].match(/:(.*?);/)[1];
          let array = [];
          for (let i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
          }
          let fileData = new Blob([new Uint8Array(array)], {
                type: mime,
              });
          let file = new File([fileData], `${new Date().getTime()}.png`, { type: mime });
          filelist.append("file", file);
          // 调上传头像接口
          this.axios.post(`/web/student/student/mine/avatarUpload`,filelist)
          .then((res) => {
              // 上传成功后调修改信息接口
             this.axios.post(`/web/student/student/mine/updateAppStu`,{
                avatar:res,
                userid:this.form.userid
                }).then(() => {
                  //重新获取信息，刷新当前头像
                  this.getAppStuDetail()
                })
                      this.$message.success("头像修改成功");
                })
          })  
                this.touxiangDialog = false
       },
  //获取学生信息
    getAppStuDetail(){
      this.axios.get(`/web/student/student/mine/getAppStuDetail`,{})
      .then((res) => {
        this.form = res
        this.form.avatar = res.avatar
      })
    },
  //显示修改头像对话框
    showEditTouxiang(){
      this.touxiangDialog = true
      let _this = this;
		// 设置头像base64
    // 其中this.form.avatar为当前头像
		this.setAvatarBase64(this.form.avatar, (base64) => {
			_this.options.img = base64;
		});
    },

    // 设置头像base64
	setAvatarBase64(src, callback) {
		let _this = this;
		let image = new Image();
		// 处理缓存
		image.src = src + '?v=' + Math.random();
		// 支持跨域图片
		image.crossOrigin = "*";
		image.onload = function () {
			let base64 = _this.transBase64FromImage(image);
			callback && callback(base64);
		}
  },
  // 将网络图片转换成base64格式
	transBase64FromImage(image) {
		let canvas = document.createElement("canvas");
		canvas.width = image.width;
		canvas.height = image.height;
		let ctx = canvas.getContext("2d");
		ctx.drawImage(image, 0, 0, image.width, image.height);
		// 可选其他值 image/jpeg
		return canvas.toDataURL("image/png");
  },
    //保存个人资料
    save(){
      this.axios.post(`/web/student/student/mine/updateAppStu`,{
        username: this.form.username,
        sex: this.form.sex,
        birthday: this.form.birthday,
        userid: this.form.userid
      }).then(() => {
        this.$message.success('保存成功')
      })
    },
 },
  
}
</script>

<style scoped src="../../style/mine/mine.css">

</style>